package com.loong.user.handler;

import com.loong.common.nacos.DynamicKey;
import com.loong.common.rest.Result;
import com.loong.common.wechat.auth.AuthUtils;
import com.loong.common.wechat.model.result.SessionKeyOrOpenIdResult;
import com.loong.common.wechat.model.result.UserRawDataResult;
import com.loong.global.constant.DynamicConfigKey;
import com.loong.global.dynamic.wechat.WeChatAppletConfig;
import com.loong.user.business.WeChatAppletLoginBusiness;
import com.loong.user.common.forehead.param.WeChatAppletLoginRequestParam;
import com.loong.user.model.UserThird;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 微信小程序授权服务
 */
@Component
public class WeChatAppletLoginHandler {
    @Resource
    private WeChatAppletLoginBusiness userThirdBusiness;
    @Resource
    AuthUtils authUtils;
    @Resource
    private DynamicKey dynamicKey;


    /**
     * 小程序登录
     * @param requestParam
     * @return
     */
    public Result weChatAppletLogin(WeChatAppletLoginRequestParam requestParam){

        WeChatAppletConfig dynamicValue = dynamicKey.getDynamicValue(DynamicConfigKey.WECHAT.WECHAT_APPLET_KEY, WeChatAppletConfig.class);
        //小程序相关信息
        String appId=dynamicValue.getAppId();
        String secret = dynamicValue.getSecret();
        String code = requestParam.getCode();
        //获取用户简单信息
        UserRawDataResult userInfo = authUtils.getUserInfo(requestParam.getRawData());
        //获取用户 sessionKey and openId
        SessionKeyOrOpenIdResult sessionKeyOrOpenId = authUtils.getSessionKeyOrOpenId(appId, secret, code);
        UserThird user = userThirdBusiness.findBy("identifier", sessionKeyOrOpenId.getOpenId());
        //检查用户是否存在
        if(ObjectUtils.isNotEmpty(user)){
            //存在

        }else {
            //不存在就入库
            //UserThird.builder()
        }
        //user-->redis


        return Result.success().build();
    }
}
